package com.sx.controller;

import com.sx.pojo.Category;
import com.sx.pojo.Person;
import com.sx.pojo.Supplier;
import com.sx.service.SupplierService;
import com.sx.service.serviceImpl.SupplierServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * 商品供应商模板
 */
@WebServlet("/supplier.action")
public class SupplierServlet extends HttpServlet {
    // 序列化版本号
    private static final long serialVersionUID = 1L;
    // 日志记录器
    private final Logger logger = LogManager.getLogger(SupplierServlet.class);
    private SupplierService supplierService = new SupplierServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");
        // 设置响应内容类型
        resp.setContentType("text/html;charset=UTF-8");

        // 获取请求参数中的action值，以确定执行的操作
        String action = req.getParameter("action");
        //获取session
        HttpSession session = req.getSession();
        Person user = null;
        if (session.getAttribute("person") == null) {
            // 重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login");
            return;
        } else {
            user = (Person) session.getAttribute("person");
        }

        // 如果action为"list"，则查询供应商和类别列表，并转发到index.jsp页面显示
        if (action != null && action.equals("list")) {
            // 调用服务获取所有供应商列表
            ArrayList<Supplier> suppliers = supplierService.getAllSupplier();
            // 调用服务获取所有类别列表
            ArrayList<Category> categoryList = supplierService.getAllCategory();
            // 将供应商和类别列表设置为请求属性
            req.setAttribute("supplierList", suppliers);
            req.setAttribute("categoryList", categoryList);
            // 设置mainRight属性，指定右侧主要内容页面
            req.setAttribute("mainRight", "/jsp/supplierList.jsp");
            // 转发请求到index.jsp页面
            req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
        } else if (action != null && action.equals("addSupplier")) {
            // 如果action为"addSupplier"，则转发到addSupplier.jsp页面，准备添加新供应商
            req.setAttribute("mainRight", "/jsp/addSupplier.jsp");
            req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
        } else if (action != null && action.equals("addCategory")) {
            req.setAttribute("mainRight", "/jsp/addCategory.jsp");
            req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
        } else if (action != null && action.equals("delete")) {
            //  删除信息操作
            // 设置响应内容类型为 JSON
            String id = req.getParameter("id");
            resp.setContentType("application/json;charset=UTF-8");
            PrintWriter out = resp.getWriter();
            if (id == null) {
                out.print("{\"status\":\"error\",\"message\":\"删除失败，请选择要删除的数据。\"}");
            } else {
                try {
                    // 这里假设你会调用相应的服务层方法进行人员删除操作
                    // 例如：PersonService.deletePerson(id);
                    // 这里为了示例，模拟删除操作成功或失败
                    // boolean success = supplierService.deleteSupplierById(id);
                    boolean success = supplierService.deleteSupplierById(user.getId(), user.getName(), 3, 3, id);
                    if (success) {
                        // 删除成功，返回成功信息
                        out.print("{\"status\":\"success\",\"message\":\"删除成功\"}");
                        // resp.sendRedirect("/person.action?action=list");
                    } else {
                        // 删除失败，返回失败信息和原因
                        out.print("{\"status\":\"error\",\"message\":\"删除失败，可能是因为关联数据存在，请先处理关联数据。\"}");
                    }
                } catch (Exception e) {
                    // 异常处理，返回错误信息
                    out.print("{\"status\":\"error\",\"message\":\"删除操作发生异常，请稍后重试。\"}");
                }

            }
        } else if (action != null && action.equals("update")) {
            try {
                String id = req.getParameter("id");
                Supplier supplier = supplierService.getSupplierById(id);
                req.setAttribute("supplier", supplier);
                req.setAttribute("mainRight", "/jsp/updateSupplier.jsp");
                req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
            } catch (Exception e) {
                resp.sendRedirect("/supplier.action?action=list");
                req.setAttribute("error", "未获取到有效的供应商ID");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String action = req.getParameter("action");
        //获取session
        HttpSession session = req.getSession();
        Person user = null;
        if (session.getAttribute("person") == null) {
            // 重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login");
            return;
        } else {
            user = (Person) session.getAttribute("person");
        }
        if (action != null && action.equals("save")) {
            /*int id = Integer.parseInt(req.getParameter("id"));*/
            String id=req.getParameter("id");
            String name = req.getParameter("name");
            String address = req.getParameter("address");
            String phone = req.getParameter("phone");
            int state = Integer.parseInt(req.getParameter("state"));
            boolean b = supplierService.addSupplier(new Supplier(id, name, address, phone, state), user.getId(), user.getName(), 1, 3, id);
            if (b) {
                resp.getWriter().write("添加成功");
            } else {
                resp.getWriter().write("添加失败");
            }
        } else if (action != null && action.equals("update")) {
            String id = req.getParameter("id");
            String name = req.getParameter("name");
            String address = req.getParameter("address");
            String phone = req.getParameter("phone");
            int state = Integer.parseInt(req.getParameter("state"));
            boolean b = supplierService.updateSupplier(new Supplier(id, name, address, phone, state), user.getId(), user.getName(), 2, 3, id);
            if (b) {
                resp.getWriter().write("修改成功");
            } else {
                resp.getWriter().write("修改失败");
            }

        }
    }
}
